package com.example.managemyself.ui.ai;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.data.repository.TaskRepository;
// import com.example.managemyself.util.AITaskManager;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * AI任务助手Fragment
 * 提供AI辅助的任务管理功能
 */
public class AITaskAssistantFragment extends Fragment {
    
    private TextView tvWelcome;
    private ChipGroup chipGroupActions;
    private RecyclerView rvRecommendations;
    private ProgressBar progressBar;
    private FloatingActionButton fabCreateTask;
    
    // private AITaskManager aiTaskManager;
    private TaskRepository taskRepository;
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    
    // private TaskRecommendationAdapter recommendationAdapter;
    // private List<AITaskManager.TaskRecommendation> recommendations = new ArrayList<>();
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        
        // aiTaskManager = AITaskManager.getInstance(requireContext());
        taskRepository = new TaskRepository(requireActivity().getApplication());
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ai_task_assistant, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        setupRecyclerView();
        setupActionChips();
        loadTodayRecommendations();
    }
    
    private void initViews(View view) {
        tvWelcome = view.findViewById(R.id.tv_welcome);
        chipGroupActions = view.findViewById(R.id.chip_group_actions);
        rvRecommendations = view.findViewById(R.id.rv_recommendations);
        progressBar = view.findViewById(R.id.progress_bar);
        fabCreateTask = view.findViewById(R.id.fab_create_task);
        
        fabCreateTask.setOnClickListener(v -> showCreateTaskDialog());
        
        // 设置欢迎文本
        tvWelcome.setText("您好！我是您的AI任务助手，准备为您提供个性化的任务管理建议。");
    }
    
    private void setupRecyclerView() {
        // 简化实现：暂时不设置推荐列表
        rvRecommendations.setLayoutManager(new LinearLayoutManager(requireContext()));
    }
    
    private void setupActionChips() {
        // 清空现有chips
        chipGroupActions.removeAllViews();
        
        // 创建功能chips
        String[] actions = {
            "评估任务情况", "今日任务推荐", "创建新任务", "优化现有任务", "完成情况分析"
        };
        
        for (String action : actions) {
            Chip chip = new Chip(requireContext());
            chip.setText(action);
            chip.setClickable(true);
            chip.setOnClickListener(v -> handleActionClick(action));
            chipGroupActions.addView(chip);
        }
    }
    
    private void handleActionClick(String action) {
        switch (action) {
            case "评估任务情况":
                evaluateTaskSituation();
                break;
            case "今日任务推荐":
                loadTodayRecommendations();
                break;
            case "创建新任务":
                showCreateTaskDialog();
                break;
            case "优化现有任务":
                showOptimizeTaskDialog();
                break;
            case "完成情况分析":
                analyzeTaskCompletion();
                break;
        }
    }
    
    private void evaluateTaskSituation() {
        progressBar.setVisibility(View.VISIBLE);
        
        // 简化实现：显示模拟的评估结果
        mainHandler.postDelayed(() -> {
            progressBar.setVisibility(View.GONE);
            String evaluation = "任务评估功能开发中，请稍后再试。";
            showEvaluationResult(evaluation);
        }, 1000);
    }
    
    private void loadTodayRecommendations() {
        progressBar.setVisibility(View.VISIBLE);
        
        // 简化实现：显示模拟的推荐
        mainHandler.postDelayed(() -> {
            progressBar.setVisibility(View.GONE);
            showInfoDialog("AI建议", "AI推荐功能开发中，请稍后再试。");
        }, 1000);
    }
    
    private void showCreateTaskDialog() {
        EditText etTaskInput = new EditText(requireContext());
        etTaskInput.setHint("请描述您想要创建的任务...");
        
        new AlertDialog.Builder(requireContext())
                .setTitle("AI创建任务")
                .setMessage("请描述您想要创建的任务，AI将为您智能分析并创建合适的任务。")
                .setView(etTaskInput)
                .setPositiveButton("创建", (dialog, which) -> {
                    String input = etTaskInput.getText().toString().trim();
                    if (!input.isEmpty()) {
                        createTaskWithAI(input);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void createTaskWithAI(String userInput) {
        progressBar.setVisibility(View.VISIBLE);
        
        // 简化实现：创建基本任务
        mainHandler.postDelayed(() -> {
            progressBar.setVisibility(View.GONE);
            
            // 创建一个基本任务
            Task newTask = new Task(userInput, "AI辅助创建的任务");
            newTask.setType("杂务");
            newTask.setImportance(5);
            newTask.setUrgency("5");
            
            taskRepository.insertTask(newTask);
            
            showInfoDialog("任务创建成功", "已为您创建任务：" + userInput);
        }, 1000);
    }
    
    private void showOptimizeTaskDialog() {
        // 获取所有待完成任务
        taskRepository.getPendingTasks().observe(getViewLifecycleOwner(), tasks -> {
            if (tasks == null || tasks.isEmpty()) {
                Toast.makeText(requireContext(), "没有待完成的任务可以优化", Toast.LENGTH_SHORT).show();
                return;
            }
            
            String[] taskTitles = new String[tasks.size()];
            for (int i = 0; i < tasks.size(); i++) {
                taskTitles[i] = tasks.get(i).getTitle();
            }
            
            new AlertDialog.Builder(requireContext())
                    .setTitle("选择要优化的任务")
                    .setItems(taskTitles, (dialog, which) -> {
                        Task selectedTask = tasks.get(which);
                        optimizeTask(selectedTask);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }
    
    private void optimizeTask(Task task) {
        progressBar.setVisibility(View.VISIBLE);
        
        // 简化实现：显示优化建议
        mainHandler.postDelayed(() -> {
            progressBar.setVisibility(View.GONE);
            showInfoDialog("任务优化", "AI优化功能开发中，建议您手动调整任务的优先级和时间安排。");
        }, 1000);
    }
    
    private void analyzeTaskCompletion() {
        taskRepository.getCompletedTasks().observe(getViewLifecycleOwner(), completedTasks -> {
            if (completedTasks == null || completedTasks.isEmpty()) {
                Toast.makeText(requireContext(), "暂无已完成的任务数据", Toast.LENGTH_SHORT).show();
                return;
            }
            
            progressBar.setVisibility(View.VISIBLE);
            
            // 简化实现：显示基本统计
            mainHandler.postDelayed(() -> {
                progressBar.setVisibility(View.GONE);
                String analysis = "您已完成 " + completedTasks.size() + " 个任务。\n\nAI分析功能开发中，敬请期待。";
                showInfoDialog("任务完成情况分析", analysis);
            }, 1000);
        });
    }
    
    private void showEvaluationResult(String evaluation) {
        new AlertDialog.Builder(requireContext())
                .setTitle("任务情况评估")
                .setMessage(evaluation)
                .setPositiveButton("知道了", null)
                .setNegativeButton("获取建议", (dialog, which) -> loadTodayRecommendations())
                .show();
    }
    

    

    
    private void showInfoDialog(String title, String message) {
        new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("知道了", null)
                .show();
    }
    
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.ai_task_assistant_menu, menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.action_refresh_recommendations) {
            loadTodayRecommendations();
            return true;
        } else if (itemId == R.id.action_task_settings) {
            // 打开任务设置
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
} 